package com.sdtv.basemodule.mvp;

import android.text.TextUtils;

import com.blankj.utilcode.util.LogUtils;
import com.google.gson.Gson;
import com.sdtv.basemodule.bean.BaseResult;
import com.sdtv.basemodule.bean.Results;
import com.sdtv.basemodule.config.AppConfig;
import com.sdtv.basemodule.rx.errorhandler.RetryWithDelay;
import com.sdtv.basemodule.rx.errorhandler.RxErrorHandler;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * @ProjectName: MediunFusion
 * @Package: com.sdtv.basemodule.mvp
 * @ClassName: IModel
 * @Description: mvp --model层基类
 * @Author: 小郭同学
 * @CreateDate: 2019-06-19 14:51
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class IModel {

    //和View层的交互接口
    private IView mIView;
    //错误处理类
    private RxErrorHandler errorHandler;
    // 显示页面请求中提示

    /**
     * 0 没loading 1 显示loading
     */

    public IModel(IView mIView) {
        this.mIView = mIView;
        this.errorHandler = AppConfig.INSTANCE.getRxErrorHandler();
    }

    /**
     * 接口请求处理
     */
    public Observable addObservable(Observable observable) {

        if (null == mIView) {
            return null;
        }
        return customObservable(observable);
    }

    /**
     * 是否需要现在加载框
     *
     * @param observable
     * @param showLoading 是否显示加载中.. true:显示  false:不显示
     * @return
     */
    public Observable addObservable(Observable observable, boolean showLoading) {
        if (null == mIView) {
            return null;
        }
        return customObservable(observable).doOnSubscribe(disposable -> {
            mIView.showLoadingDialog();
        });
    }

    /**
     * 真正的接口处理方法 以及回调处理
     *
     * @param observable
     * @return
     */
    private Observable customObservable(Observable<String> observable) {
        return observable
                .compose(mIView.getProvider().bindToLifecycle())
                .retryWhen(new RetryWithDelay(2, 2))
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
//                .doFinally(() -> {
//                    if (mIView != null) {
//                        mIView.hideLoadingDialog();
//                    }
//                })
                .doOnNext(result -> {
                    if (!TextUtils.isEmpty(result) && !result.contains("domain")) {
                        // 判断是否有登出 或者 token过期
                        BaseResult baseResult = new Gson().fromJson(result, BaseResult.class);
                        if (null != baseResult && 200 == baseResult.getCode()) {
                            Results results = baseResult.getResults();
                            if (results.getRet() == 405 || results.getRet() == 403) {
                                //提示用户被登出--或者token过期了 弹窗提示
                                mIView.showKickOutDialog(results.getMsg());
                            }
                        }
                    }
                    if (mIView != null) {
                        mIView.hideLoadingDialog();
                    }
                })
                .doOnError(throwable -> {
                    LogUtils.e("doOnError--这里是服务器异常----" + throwable);
                    if (mIView != null) {
                        //这里是负责展示错误页面的 ----
                        mIView.onError();
                    }
                    if (null != errorHandler) {
                        errorHandler.getErrorHandlerFactory().handleError(throwable);
                    }
                });
    }
}
